<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="dialogTitle"
    width="30%"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      status-icon
      :model="form"
      label-width="80px"
      :rules="rules"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="用户名ID" prop="loginId">
        <el-input v-model="form.loginId" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio label="男" />
          <el-radio label="女" />
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="密码"
        prop="password"
        v-if="dialogTitle === '添加用户'"
      >
        <el-input v-model="form.password" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item
        label="确认密码"
        prop="checkPass"
        v-if="dialogTitle === '添加用户'"
      >
        <el-input v-model="form.checkPass" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="邮件" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="联系方式" prop="telephone">
        <el-input v-model.number="form.telephone" />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleConfirm">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'
import { addOrModifyUser } from '@/api/authority.js'
import { ElMessage } from 'element-plus'

const props = defineProps({
  dialogTitle: {
    type: String,
    required: true,
    default: ''
  },
  dialogTableValue: {
    type: Object,
    default: () => {} // 空对象
  },
  dialogVisible: {
    type: Boolean,
    default: false
  }
})
const initForm = () => {
  return {
    username: '',
    loginId: '',
    gender: '',
    password: '',
    checkPass: '',
    email: '',
    telephone: '',
    address: ''
  }
}
const form = ref(initForm())

// Vue3中监视对于对象中的属性需要使用如下方式
watch(
  () => props.dialogTableValue,
  () => {
    // console.log(props.dialogTableValue)
    form.value = props.dialogTableValue
  },
  { deep: true, immediate: true }
)
const emits = defineEmits(['update:modelValue', 'initTableList'])
const formRef = ref(null)
const checkPass = ref('')

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback('请输入密码')
  } else {
    if (form.value.checkPass !== '') {
      // validateField：对部分表单校验的方法
      formRef.value.validateField('checkPass')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const checkPhone = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('手机号不能为空'))
  }
  setTimeout(() => {
    if (!Number.isInteger(value)) {
      callback(new Error('请输入数字值'))
    } else {
      // 将number类型转字符串类型然后判断字符串长度
      if ((value + '').length !== 11) {
        callback(new Error('手机号应该为11位,请重新输入'))
      } else {
        callback()
      }
    }
  }, 1000)
}

const rules = ref({
  address: [
    {
      required: true,
      message: 'Please input address',
      trigger: 'blur'
    }
  ],
  gender: [
    {
      required: true,
      message: 'Please select gender',
      trigger: 'change'
    }
  ],
  loginId: [
    {
      required: true,
      message: 'Please input loginId',
      trigger: 'change'
    }
  ],
  username: [
    {
      required: true,
      message: 'Please input username',
      trigger: 'blur'
    },
    { min: 1, max: 15, message: 'Length should be 1 to 15', trigger: 'blur' }
  ],
  email: [
    {
      required: true,
      message: 'Please input email address',
      trigger: 'blur'
    },
    {
      type: 'email',
      message: 'Please input correct email address',
      trigger: ['blur', 'change']
    }
  ],
  telephone: [{ validator: checkPhone, trigger: 'blur' }],
  password: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }]
})
const handleClose = () => {
  emits('update:modelValue', false)
  Object.assign(form.value, initForm())
}

const handleConfirm = () => {
  // 统一表单校验 接口设计是包括修改和删除
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await addOrModifyUser(form.value)
        ElMessage({
          type: 'success',
          message:
            props.dialogTitle === '添加用户' ? '添加用户成功' : '修改用户成功',
          duration: 1500
        })
        handleClose()
        emits('initTableList')
      } catch (error) {
        ElMessage({
          type: 'error',
          message: error,
          duration: 1500
        })
      }
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped></style>
